package dahuiji.login.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dahuiji.common.entity.User;
import dahuiji.common.servlet.BaceServlet;
import dahuiji.login.service.LoginService;

public final class Login extends BaceServlet {

	/**
	 * Constructor of the object.
	 */
	public Login() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	@Override
	public String perform(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String codeinput = request.getParameter("vf");
		String result = null;
		String nextPage = null;// 跳转页面
		HttpSession session = request.getSession();
		String code = (String) session.getAttribute("verifycode");
		RequestDispatcher rd;
		LoginService login=null;
		if (name == null || name.equals("")) {
			result = "请输入用户名，密码，验证码";
			nextPage = "/view/login/login.jsp";
			request.setAttribute("msg", result);
		}
		else if (password == null || password.equals("")) {
			result = "请输入用户名，密码，验证码";
			nextPage = "/view/login/login.jsp";
			request.setAttribute("msg", result);
		}
		else if (codeinput == null || codeinput.equals("")) {
			result = "请输入用户名，密码，验证码";
			nextPage = "/view/login/login.jsp";
			request.setAttribute("msg", result);
		}
		else if (codeinput != null && !codeinput.equals("")) {
			if (!codeinput.equals(code)) {
				result = "验证码不对";
				nextPage = "/view/login/login.jsp";
				request.setAttribute("msg", result);
			}else{
				login=new LoginService();
				User u=login.login(name, password);
				if(u!=null){
					HttpSession session2=request.getSession();
					session2.setAttribute("user", u);
					nextPage = "/view/index.jsp";
				}else{
					result = "用户名或者密码错误";
					nextPage = "/view/login/login.jsp";
					request.setAttribute("msg", result);
				}
			}

		}
	
		rd = getServletContext().getRequestDispatcher(nextPage);
		rd.forward(request, response);

		return nextPage;

	}

}
